package org.ypx.center.controller.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ypx.center.controller.UserController;
import org.ypx.center.service.IUserService;
import org.ypx.db.entity.User;
import org.ypx.shared.common.Result;
import org.ypx.web.App;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author tingwen
 * @date 2017/3/28 21:06
 * @description
 */
@Controller
@RequestMapping("user")
public class UserControllerImpl extends BaseControllerImpl<User> implements UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("login.do")
    @ResponseBody
    public Result<User> login(User user, HttpSession session) {
        //User user = null;
        Result<User> result = userService.loadUserByUsernameAndPassword(user);
        if (result != null) {
            // logger.info("登陆成功：{}", result);
            session.setAttribute(App.USER_SESSION_KEY, result.getData());
            return result;
        } else {
            return result;
        }
    }

    @RequestMapping("findAll.do")
    @ResponseBody
    public Result<List<User>> findAll(User user, HttpSession session) {
        //User user = null;
        Result<List<User>> results = userService.selectAll();
        return results;
    }


    @RequestMapping("index.do")
    @ResponseBody
    public void login(User user, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        //User user = null;
        request.getRequestDispatcher("/production/index.html").forward(request, response);
    }

    @RequestMapping("register.do")
    @ResponseBody
    @Override
    public Result<List<User>> register(User user) {
        return userService.register(user);
    }

    @RequestMapping("batchRegister.do")
    @ResponseBody
    @Override
    public void batchRegister(List<User> users) {
        users.forEach(user ->
                this.register(user)
        );
    }

    @RequestMapping("batchDelete.do")
    @ResponseBody
    @Override
    public void batchDelete(@RequestParam(value = "selectedIds[]", required = true) Long[] selectedIds) {
        userService.batchDelete(selectedIds);
    }
}
